package com.module.overview.ui.cardHistoryDetails.provider

import android.graphics.Typeface
import android.view.View
import android.widget.TextView
import com.chad.library.adapter.base.provider.BaseItemProvider
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.common.app.core.RouterHub
import com.common.app.data.bean.CalendarDay
import com.common.app.data.bean.KeyBundle
import com.common.app.data.bean.KeyPre
import com.common.app.data.bean.home.ScoringFactorsModel
import com.common.app.data.bean.overView.HistoryDetailsModel
import com.common.app.data.repository.HomeApi
import com.common.app.helper.RouterHelper
import com.common.app.utls.TimeUtils
import com.common.base.app.extras.doOnIOThread
import com.common.base.app.extras.doOnUiThread
import com.common.base.app.extras.setOnClickListener
import com.common.base.app.extras.yes
import com.common.base.data.CommonBean
import com.common.base.utils.AppUtils
import com.common.base.utils.JsonUtils
import com.common.base.utils.MathUtil
import com.common.base.utils.SpUtilsManagement
import com.common.base.utils.SpanUtils
import com.common.base.utils.ViewUtils
import com.common.base.utils.ViewUtils.getString
import com.module.ble.repo.UserStepsRelatedRecordRepo
import com.module.ble.repo.SportRecordRepo
import com.module.ble.repo.UserCalorieRepo
import com.module.ble.utils.AllCardTypeConfig
import com.module.overview.R
import com.module.overview.ui.widget.AnimatedTripleRingView
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.launch
import rxhttp.toFlow
import rxhttp.wrapper.param.RxHttp
import java.util.concurrent.TimeUnit

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2025/7/13
 *
 * 描述：活动-活动状态卡片
 *
 * 修订历史：完成度100%
 *
 */
class OvActivityStateCardProvider(time:Long,
                                  override val itemViewType: Int = AllCardTypeConfig.TYPE_CARD_ACTIVITY_STATE_VALUE,
                                  override val layoutId: Int = R.layout.overview_activity_state_crad_provider
) : BaseItemProvider<HistoryDetailsModel>() {

    private var curTime = time

    private var requestJob: Job? = null
    var scope = CoroutineScope(Dispatchers.IO)


    private var tripleRingView: AnimatedTripleRingView? = null
    private var tvScoreSplicing : TextView? = null
    private var tvScoreTime: TextView? = null
    private var tvSportsSteps : TextView? = null
    private var tvConsumeCalories : TextView? = null
    private var tvSportsDuration : TextView? = null

    var totalStepsNum = 0L
    var totalCalorie = 0L
    var totalExerciseDuration = 0L

    var stepsProgress = 0f
    var calorieProgress = 0f
    var exerciseDurationProgress = 0f

    init {
    }

    override fun convert(helper: BaseViewHolder, item: HistoryDetailsModel) {

        tripleRingView?.setProgress(listOf(stepsProgress.toInt(), calorieProgress.toInt(), exerciseDurationProgress.toInt()))

        getAcScoringFactors()

        getTheDayActivityData()
    }

    override fun onViewHolderCreated(viewHolder: BaseViewHolder, viewType: Int) {
        tripleRingView = viewHolder.getView(R.id.tripleRingView)
        tvScoreSplicing = viewHolder.getView(R.id.tvScoreSplicing)
        tvScoreTime = viewHolder.getView(R.id.tvScoreTime)
        tvSportsSteps = viewHolder.getView(R.id.tvSportsSteps)
        tvConsumeCalories = viewHolder.getView(R.id.tvConsumeCalories)
        tvSportsDuration = viewHolder.getView(R.id.tvSportsDuration)

        tvScoreSplicing?.setOnClickListener(onClick = object : View.OnClickListener {
            override fun onClick(p0: View?) {
                RouterHelper.navigationPostcard(RouterHub.ROUTER_HOME_SCORING_FACTORS)
                    .withInt(KeyBundle.BUNDLE_KEY, 2)
                    .withString(KeyBundle.EXPAND_DATA, TimeUtils.getYearMonthDay(curTime))
                    .navigation()
            }
        })
        super.onViewHolderCreated(viewHolder, viewType)
    }

    /**
     * 获取当天活动信息
     */
    fun getTheDayActivityData(){
        if (curTime <=0) return

        doOnIOThread {
            UserStepsRelatedRecordRepo.instance.findByOneDay(curTime)?.let { originalListIt->
                if (originalListIt.isNullOrEmpty()) return@doOnIOThread

//                val listItStr = JsonUtils.toJson(originalListIt)

                totalStepsNum = 0L

                originalListIt.forEach { beanIt->
                    totalStepsNum += beanIt.step.toInt()
                }

                doOnUiThread {
                    tvSportsSteps?.text = totalStepsNum.toString()

                    stepsProgress = (MathUtil.div9(totalStepsNum.toString(),SpUtilsManagement.getInt(KeyPre.KEY_STEP_TARGET_VALUE, 6000).toString()) * 100).toFloat()

                    tripleRingView?.setProgressWithAnimation(listOf(stepsProgress, calorieProgress, exerciseDurationProgress))
                }
            }
        }

        getTheDayCalorieData()
    }


    /**
     * 获取当天卡路里信息
     */
    fun getTheDayCalorieData(){
        if (curTime <=0) return

        doOnIOThread {
            UserCalorieRepo.instance.findByOneDay(curTime)?.let { originalListIt->
                if (originalListIt.isNullOrEmpty()) return@doOnIOThread

//                val listItStr = JsonUtils.toJson(originalListIt)

                totalCalorie = 0L

                originalListIt.forEach { beanIt->
                    totalCalorie += beanIt.calorie.toLong()
                }

                doOnUiThread {
                    tvConsumeCalories?.text = totalCalorie.toString()

                    calorieProgress = (MathUtil.div9(totalCalorie.toString(),SpUtilsManagement.getInt(KeyPre.KEY_CALORIE_TARGET_VALUE, 300).toString()) * 100).toFloat()

                    tripleRingView?.setProgressWithAnimation(listOf(stepsProgress, calorieProgress, exerciseDurationProgress))
                }
            }
        }

        getTheDaySportsData()
    }

    /**
     * 获取当天运动信息
     */
    fun getTheDaySportsData(){
        if (curTime <=0) return

        doOnIOThread {
            SportRecordRepo.instance.findAllByDay(curTime)?.let { originalListIt->
                if (originalListIt.isNullOrEmpty()) {
                    tripleRingView?.setProgressWithAnimation(listOf(stepsProgress, calorieProgress, exerciseDurationProgress))
                    return@let
                }
//                val listItStr = JsonUtils.toJson(originalListIt)
                totalExerciseDuration = 0
                originalListIt.forEach { beanIt->
                    totalExerciseDuration+= beanIt.endTs-beanIt.startTs
                }
                exerciseDurationProgress = (MathUtil.div9(TimeUnit.MILLISECONDS.toMinutes(totalExerciseDuration).toString(),SpUtilsManagement.getInt(KeyPre.KEY_AC_DURATION_TARGET_VALUE, 45).toString()) * 100).toFloat()

                val tvLastSList = TimeUtils.formatTimeToList(totalExerciseDuration)

                doOnUiThread {
                    tvSportsDuration?.let { viewIt ->
                       val spanBuilderTemp = SpanUtils.create()
                        (tvLastSList[1]>0).yes {
                            spanBuilderTemp
                                .addSection(tvLastSList[1].toString())
                                .addForeColorSection(
                                AppUtils.getString(R.string.common_hours_hint), ViewUtils.getColor(R.color.c_7f7f7f))
                                .setAbsSize(AppUtils.getString(R.string.common_hours_hint), 12)
                                .setStyle(AppUtils.getString(R.string.common_hours_hint), Typeface.NORMAL)
                        }
                        spanBuilderTemp
                            .addSection(tvLastSList[2].toString())
                            .addForeColorSection(AppUtils.getString(R.string.common_minutes_hint), ViewUtils.getColor(R.color.c_7f7f7f))
                            .setAbsSize(AppUtils.getString(R.string.common_minutes_hint), 12)
                            .setStyle(AppUtils.getString(R.string.common_minutes_hint), Typeface.NORMAL)
                            .showIn(viewIt)
                    }

                    tripleRingView?.setProgressWithAnimation(listOf(stepsProgress, calorieProgress, exerciseDurationProgress))
                }
            }
        }
    }



    // 手动取消请求
    fun cancelRequest() {
        requestJob?.cancel()
        requestJob = null
    }

    private fun getAcScoringFactors() {
        // 取消之前的请求
        requestJob?.cancel()

        requestJob = scope.launch {
            RxHttp.postJson(HomeApi.GET_ACTIVITY_SCORING_FACTORS)
                .add("date", TimeUtils.getYearMonthDay(curTime))
                .toFlow<CommonBean<ScoringFactorsModel>>()
                .catch { e ->
                    // 处理异常
                }.collect { responseIt->
                    responseIt.isSuccess().yes {
                        responseIt.Data?.let { dataIt->
                            doOnUiThread {
                                tvScoreSplicing?.text = getString(
                                    R.string.overview_activity_score_splicing,
                                    dataIt.total_score.toInt().toString()
                                )
                                tvScoreTime?.text = "${getString(R.string.overview_activity_deadline_hint)}${TimeUtils.getHourMinute(TimeUtils.getTimeDateLong())}"
                            }
                        }
                    }
                }
        }
    }
}